package com.nuoniu.sibanyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SysAgreement;
import com.nuoniu.sibanyun.entity.dto.AgreementDto;
import com.nuoniu.sibanyun.entity.dto.AgreementSearchDto;
import com.nuoniu.sibanyun.mapper.SysAgreementMapper;
import com.nuoniu.sibanyun.service.ISysAgreementService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-08-31
 */
@Service
public class SysAgreementServiceImpl extends ServiceImpl<SysAgreementMapper, SysAgreement> implements ISysAgreementService {

    @Override
    public boolean saveAgreement(AgreementDto agreementDto) {
        UserInfo userInfo = UserThreadLocal.get();
        SysAgreement sysAgreement = new SysAgreement();
        BeanUtils.copyProperties(agreementDto,sysAgreement);
        if(null != sysAgreement.getId()){
            sysAgreement.setLastId(sysAgreement.getId().intValue());
        }
        sysAgreement.setCreateUserId(userInfo.getUserId());
        sysAgreement.setCreateUserName(userInfo.getRealName());
        sysAgreement.setCreateDate(LocalDateTime.now());
        boolean save = save(sysAgreement);
        if(!save){
            throw new NuoNiuException("保存失败");
        }
        return true;
    }

    @Override
    public List<SysAgreement> last() {
        List<SysAgreement> last = baseMapper.last();
        return last;
    }

    @Override
    public List<SysAgreement> historyList(AgreementSearchDto agreementSearchDto) {
        QueryWrapper<SysAgreement> queryWrapper = new QueryWrapper();
        if(StringUtils.isNotBlank(agreementSearchDto.getCode())){
            queryWrapper.eq("code",agreementSearchDto.getCode());
        }
        if(StringUtils.isNotBlank(agreementSearchDto.getContent())){
            queryWrapper.like("content",agreementSearchDto.getContent());
        }
        List<SysAgreement> list = list(queryWrapper);
        return list;
    }

    @Override
    public String getAgreement(String code) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("content");
        queryWrapper.eq("code",code);
        queryWrapper.eq("status",0);
        queryWrapper.orderByDesc("create_date");
        queryWrapper.last("limit 1");
        SysAgreement one = getOne(queryWrapper,false);
        if(null != one){
            return one.getContent();
        }
        return null;
    }
}
